"""
将代码按每10秒进行裁剪
"""
import os
import subprocess

# 输入和输出的主目录（改动）
source_folder = r'D:\file\postgrad\experiment\video_2\split_video_20'
output_folder = r'D:\file\postgrad\experiment\video_2\split_video_10'

# 确保目标文件夹存在
if not os.path.exists(output_folder):
    os.makedirs(output_folder)

# 跳过的文件夹名称



skip_folders = ['muntjac', 'silver pheasant']

# 遍历源文件夹中的所有文件
for root, dirs, files in os.walk(source_folder):


    # 检查当前文件夹是否在跳过列表中
    folder_name = os.path.basename(root)
    if folder_name in skip_folders:
        print(f"Skipping folder: {folder_name}")
        continue  # 跳过此文件夹

    for file in files:
        if file.endswith(('.mp4', '.avi', '.mkv')):  # 检查视频文件格式
            input_file = os.path.join(root, file)

            # 计算相对于 source_folder 的相对路径，保持原始文件夹结构
            relative_path = os.path.relpath(root, source_folder)
            output_subfolder = os.path.join(output_folder, relative_path)

            # 确保目标子文件夹存在
            if not os.path.exists(output_subfolder):
                os.makedirs(output_subfolder)

            # 获取视频时长
            command_get_duration = [
                'ffprobe', '-v', 'error', '-select_streams', 'v:0', '-show_entries',
                'stream=duration', '-of', 'default=noprint_wrappers=1:nokey=1', input_file
            ]
            try:
                result = subprocess.run(command_get_duration, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
                if result.returncode != 0:
                    print(f"Error getting duration for {input_file}: {result.stderr}")
                    continue  # 跳过此文件

                duration = result.stdout.strip()
                if not duration:
                    print(f"No duration found for {input_file}")
                    continue  # 跳过此文件

                duration = float(duration)
            except ValueError as e:
                print(f"Error converting duration to float for {input_file}: {e}")
                continue  # 跳过此文件

            # 计算分段数量
            num_segments = int(duration // 10) + 1  # 每 10 秒一段，最后一段可能不足 10 秒

            # 构建裁剪后文件的输出模板，使用原文件名加上 _1, _2 作为后缀
            base_name = os.path.splitext(file)[0]  # 去掉文件扩展名

            # 使用 ffmpeg 进行裁剪，每 10 秒分一段，使用重新编码确保输出正确
            for i in range(num_segments):
                start_time = i * 10
                output_file = os.path.join(output_subfolder, f'{base_name}_{i+1}.mp4')

                command = [
                    'ffmpeg', '-i', input_file, '-ss', str(start_time), '-t', '10',
                    '-c:v', 'libx264', '-c:a', 'aac', '-strict', 'experimental',
                    '-avoid_negative_ts', 'make_zero', output_file
                ]
                subprocess.run(command)

            print(f"视频 {input_file} 已裁剪并保存到 {output_subfolder}")

